package canraid.gui.listeners;

import android.R.color;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import canraid.agent.Iagent;
import canraid.agent.implementations.BluetoothAgent;
import canraid.agent.implementations.FileAgent;
import canraid.agent.implementations.NetworkAgent;
import canraid.config.Properties;
import canraid.debug.Level;
import canraid.debug.Logger;
import canraid.gen.R;
import canraid.gui.BluetoothList;
import canraid.gui.MainCanraid;


public class AgentController implements OnClickListener
{	
	private final String PATH=Environment.getExternalStorageDirectory().getAbsolutePath();
	private final String FILENAME="fileCanraid.txt";
	
	private MainCanraid parentActivity=null;
	private Iagent bluetoothAgent=null;
	private Iagent fileAgent=null;
	private Iagent networkAgent=null;
	private Handler guiHandler=null;
	private String addressBTDevice=null;
	private String OFF=null;
	private String ON=null;
	private EditText outputText=null;
	private EditText inText=null;
	private boolean secureConnection=true;
	
	public boolean pendingSwitchBTOn=false;
	
	public AgentController(MainCanraid parentActivity, Handler guiHandler){
        Logger.setLog(this,Level.ASSERT,"ButtonAgentListener().");
        
		this.parentActivity=parentActivity;
		this.guiHandler=guiHandler;
		OFF=parentActivity.getString(canraid.gen.R.string.off);
		ON=parentActivity.getString(canraid.gen.R.string.on);
		outputText=(EditText) parentActivity.findViewById(canraid.gen.R.id.textChatMultiline);
		inText=(EditText) parentActivity.findViewById(canraid.gen.R.id.textChatSingleLine);
		
	}
	
	public void onClick(View v) {
		if (fileAgent!=null){
			if (fileAgent.isFired() && !fileAgent.isRunning()){ 
				fileAgent=null;
			}
		}
		
		if (networkAgent!=null){
			if (networkAgent.isFired() && !networkAgent.isRunning()){ 
				networkAgent=null;
			}
		}
		
		if (bluetoothAgent!=null){
			if (bluetoothAgent.isFired() && !bluetoothAgent.isRunning()){ 
				bluetoothAgent=null;
			}
		}
		
		switch (v.getId()){
		case canraid.gen.R.id.buttonBluetooth:
			onClickBluetooth(v);
			break;
		case canraid.gen.R.id.buttonFile:
			onClickFile(v);
			break;
		case canraid.gen.R.id.buttonNetwork:
			onClickNetwork(v);
			break;
		case canraid.gen.R.id.button_send:
			onClickSend(v);
			break;
		}
	}
	
	
	public void onClickBluetooth(View v) {
        Logger.setLog(this,Level.ASSERT,"onClickBluetooth().");
        Button bBT =(Button) v;
        
        if (bBT.getText().equals(OFF)){
        	//OFF-->ON
        	pendingSwitchBTOn= true;
        	requestToActivateBluetooth();
    	    Logger.setLog(this,Level.INFO,"onClickBluetooth(). OFF->ON. Switch immediately? "+(pendingSwitchBTOn?"NO.":"YES."));
        	
        }else if(bBT.getText().equals(ON)){
        	//ON -> OFF
        	pendingSwitchBTOn=false;
        	
        	if (bluetoothAgent==null){
    	        Logger.setLog(this,Level.ERROR,"onClickBluetooth(). Bluetooth Null (ON->OFF).");
    	        bBT.setText(OFF);
        		return;
        	}
        	bluetoothAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_STOP, bluetoothAgent.getAgentName()).sendToTarget();
	        Logger.setLog(this,Level.ASSERT,"onClickBluetooth(). Done.");
        }
        else{
	        Logger.setLog(this,Level.WARNING,"onClickBluetooth(). Click Status not found: >"+bBT.getText()+"<");
	        pendingSwitchBTOn=false;
        }
		
	}
	
	public void onClickFile(View v) {
        Logger.setLog(this,Level.ASSERT,"onClickFile().");
        
        Button bFL=(Button)v;
        
        if (bFL.getText().equals(OFF)){
        	//OFF-->ON
        	if (fileAgent==null){
        		fileAgent= new FileAgent(PATH,FILENAME);
        		fileAgent.addExternalHandlers(guiHandler);
    	        Logger.setLog(this,Level.INFO,"onClickFile(). OFF->ON. (newAgent created)");
        	}
        	if (bluetoothAgent!=null){
        		bluetoothAgent.addExternalHandlers(fileAgent.getHandler());
    	        Logger.setLog(this,Level.ASSERT,"onClickFile(). Handler File added to BluetoothAgent.");
        	}
        	
        	fileAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_START, fileAgent.getAgentName()).sendToTarget();

	        Logger.setLog(this,Level.INFO,"onClickFile(). Done.");
        }else if(bFL.getText().equals(ON)){
        	//ON -> OFF
        	if (fileAgent==null){
    	        Logger.setLog(this,Level.ERROR,"onClickFile(). FileAgent Null (ON->OFF)");
    	        bFL.setText(OFF);
        		return;
        	}
        	fileAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_STOP, fileAgent.getAgentName()).sendToTarget();
	        Logger.setLog(this,Level.ASSERT,"onClickFile(). Done.");
        }
        else{
	        Logger.setLog(this,Level.ERROR,"onClickFile(). Click Status not found: >"+bFL.getText()+"<");
        }
		
	}
	
	public void onClickNetwork(View v) {
        Logger.setLog(this,Level.ASSERT,"onClickNetwork().");
        
        Button bNTW=(Button)v;
        
        if (bNTW.getText().equals(OFF)){
        	//OFF-->ON
        	if (networkAgent==null){
        		networkAgent= new NetworkAgent(parentActivity);
        		networkAgent.addExternalHandlers(guiHandler);
    	        Logger.setLog(this,Level.INFO,"onClickNetwork(). OFF->ON. (newAgent created)");
        	}
        	if (bluetoothAgent!=null){
        		bluetoothAgent.addExternalHandlers(networkAgent.getHandler());
    	        Logger.setLog(this,Level.ASSERT,"onClickNetwork(). Handler File added to BluetoothAgent.");
        	}
        	
        	networkAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_START, networkAgent.getAgentName()).sendToTarget();

	        Logger.setLog(this,Level.INFO,"onClickNetwork(). Done.");
        }else if(bNTW.getText().equals(ON)){
        	//ON -> OFF
        	if (networkAgent==null){
    	        Logger.setLog(this,Level.ERROR,"onClickNetwork(). NetworkAgent Null (ON->OFF)");
    	        bNTW.setText(OFF);
        		return;
        	}
        	networkAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_STOP, networkAgent.getAgentName()).sendToTarget();
	        Logger.setLog(this,Level.ASSERT,"onClickNetwork(). Done.");
        }
        else{
	        Logger.setLog(this,Level.ERROR,"onClickNetwork(). Click Status not found: >"+bNTW.getText()+"<");
        }
		
	}
	
	public boolean requestToActivateBluetooth(){
		Logger.setLog(this,Level.ASSERT,"requestToActivateBluetooth().");
		
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
        	String text= "Bluetooth not available.";
        	Toast.makeText(parentActivity, text, Toast.LENGTH_LONG).show();
        	Logger.setLog(this,Level.ERROR,"requestToActivateBluetooth(). "+text);
        	return false;
        }else if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            parentActivity.startActivityForResult(enableIntent, Iagent.REQUEST_ENABLE_BT);
            Logger.setLog(this,Level.INFO,"requestToActivateBluetooth(). Request to activate Bluetooth.");
            return false;
        }else if(addressBTDevice==null || bluetoothAgent==null){
        	try{
        		Logger.setLog((Object)this,Level.INFO,"requestToActivateBluetooth(). Request to choose Bluetooth Device: launching BluetoothList...");
        		Intent serverIntent = new Intent(parentActivity, BluetoothList.class);
        		parentActivity.startActivityForResult(serverIntent, Iagent.REQUEST_CHOICE_DEVICE_BT);
        	}catch(Exception e){
        		Logger.setLog((Object)this,Level.ERROR,"requestToActivateBluetooth(). Launching BluetoothList failed! ERROR:"+e.getMessage());
        	}
            return false;
        }else if (pendingSwitchBTOn){
    		bluetoothAgent.getHandler().obtainMessage(Iagent.REQUEST_AGENT_START, bluetoothAgent.getAgentName()).sendToTarget();
        	pendingSwitchBTOn=false;
        	return true;
    	}
        
        Logger.setLog(this,Level.INFO,"requestToActivateBluetooth().  Bluetooth Ready to receive.");
        return true;
	}
	
	public void responseToActivateBluetooth(int requestCode, int resultCode, Intent data) {
		Logger.setLog(this,Level.ASSERT,"responseToActivateBluetooth().");
		
        if (requestCode==Iagent.REQUEST_ENABLE_BT){
            if (resultCode == Activity.RESULT_OK) {
            	Logger.setLog((Object)this,Level.INFO,"responseToActivateBluetooth(). Bluetooth enable.");
            	//continua l'attivazione.
            	requestToActivateBluetooth();
            } 
            else {
            	String text= "Bluetooth not enabled.";
            	Toast.makeText(parentActivity, text, Toast.LENGTH_LONG).show();
            	Logger.setLog((Object)this,Level.WARNING,"responseToActivateBluetooth(). "+text);
            	pendingSwitchBTOn=false;
            }
        }
        else if (requestCode==Iagent.REQUEST_CHOICE_DEVICE_BT){
            if (resultCode == Activity.RESULT_OK) {
            	addressBTDevice = data.getExtras().getString(BluetoothList.DEVICE_ADDRESS);
            	if (bluetoothAgent==null){
            		bluetoothAgent=new BluetoothAgent(addressBTDevice,secureConnection);
            		bluetoothAgent.addExternalHandlers(guiHandler);
            		Logger.setLog(this,Level.INFO,"responseToActivateBluetooth(). OFF(pending)->ON. (newAgent created)");
            	}
            	Logger.setLog((Object)this,Level.INFO,"responseToActivateBluetooth(). Device Bluetooth is chosen");
            	
            	requestToActivateBluetooth();
            } 
            else {
            	String text= "Device Bluetooth is not choosen";
            	Toast.makeText(parentActivity, text, Toast.LENGTH_LONG).show();
            	Logger.setLog((Object)this,Level.WARNING,"responseToActivateBluetooth(). "+text);
            	pendingSwitchBTOn=false;
            }
        }
    }
	
	public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_bt_secure:
        	item.setChecked(!item.isChecked());
            setSecureConnection(item.isChecked());
            Logger.setLog(this,Level.INFO,"onOptionsItemSelected(). SecureConnection set: "+item.isChecked()+" (it was "+!item.isChecked()+")");
            return true;
        }
        return false;
    }
	
	public void destroy(){
		Logger.setLog(this,Level.ASSERT,"destroy().");
		
		if (bluetoothAgent!=null){
			bluetoothAgent.stopPolling();
			bluetoothAgent.close();
		}
		
		if (fileAgent!=null){
			fileAgent.stopPolling();
			fileAgent.close();
		}
		
		if (networkAgent!=null){
			networkAgent.stopPolling();
			networkAgent.close();
		}
	}

	public boolean isSecureConnection() {
		return secureConnection;
	}

	public void setSecureConnection(boolean secureConnection) {
		this.secureConnection = secureConnection;
	}

	public void onClickSend(View v) {
		Logger.setLog(this,Level.ASSERT,"onClickSend().");
		
        String message = inText.getText().toString();
        if (message==null)
        	message="";
        
        String messageBT=message+ (char)13;
        String messageTXT=message;
        String messageNTW=message;
        
    	if (bluetoothAgent!=null && Properties.MODE==Properties.TECHNICIAN)
    		bluetoothAgent.getHandler().obtainMessage(Iagent.FROM_TEXT, messageBT.getBytes().length, -1, messageBT.getBytes()).sendToTarget();
    	
    	if (fileAgent!=null && Properties.MODE==Properties.TECHNICIAN)
    		fileAgent.getHandler().obtainMessage(Iagent.FROM_TEXT, messageTXT.getBytes().length, -1, messageTXT.getBytes()).sendToTarget();
    	
    	if (networkAgent!=null)
    		networkAgent.getHandler().obtainMessage(Iagent.FROM_TEXT, messageNTW.getBytes().length, -1, messageNTW.getBytes()).sendToTarget();
    	
    	guiHandler.obtainMessage(Iagent.FROM_TEXT, messageTXT.getBytes().length, -1, messageTXT.getBytes()).sendToTarget();
    	
    	Logger.setLog(this,Level.INFO,"onClickSend(). Sent message("+message+")");
	}
} ;
